package com.hhxy.utils;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.commons.lang3.RandomUtils;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @auther:Lu Yao
 * @date:2022/6/4
 * @description: 生成pdf文件
 **/

public class PdfUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(PdfUtil.class);

    public static String createPdf() {
        Document document = new Document(PageSize.A4, 30, 0, 30, 30);
        //创建文件路径
      /* File file = new File("src/main/java/com/hhxy/utils");
       if (!file.exists()){
           file.mkdirs();
       }*/
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File("test" + RandomUtils.nextLong() + ".pdf")));
            // 设置每行的间距
            writer.setInitialLeading(30);
            document.open();

            //pdf分页事件

            //中文字体,解决中文不能显示问题
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            //设置样式
            Font blueFont = new Font(bfChinese, 20f, Font.NORMAL, BaseColor.BLACK);
            Font titleFont = new Font(bfChinese, 15f, Font.BOLD, BaseColor.BLACK);

            //设置文档标题
            Paragraph titleGraph = new Paragraph("中国人民银行公告", titleFont);
            titleGraph.setSpacingBefore(50);
            titleGraph.setAlignment(PdfPCell.ALIGN_CENTER);
            document.add(titleGraph);
            //表格设置
            int tableCloumns = 30;
            PdfPTable table = new PdfPTable(tableCloumns);
            /*table.setWidths(new int[]{6,9});*/
            table.setSpacingAfter(10);
            table.setSpacingBefore(10);
            //跨页处理
          /*  table.setSplitLate(false);
            table.setSplitRows(true);*/
            table.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);

            table.addCell(createCell("状态中心", blueFont, Element.ALIGN_LEFT, tableCloumns, true));


            table.addCell(createCell("和谐0", blueFont, Element.ALIGN_LEFT, 6, true));
            table.addCell(createCell("公正", blueFont, Element.ALIGN_LEFT, 9, true));

            table.addCell(createCell("和谐2", blueFont, Element.ALIGN_LEFT, 6, true));
            table.addCell(createCell("公正", blueFont, Element.ALIGN_LEFT, 9, true));

            table.addCell(createCell("和谐202", blueFont, Element.ALIGN_LEFT, 6, true));
            table.addCell(createCell("公正", blueFont, Element.ALIGN_LEFT, 9, true));
            table.addCell(createCell("", blueFont, Element.ALIGN_LEFT, 6, true));
            table.addCell(createCell("", blueFont, Element.ALIGN_LEFT, 9, true));
          /*  table.addCell(createCell("和谐",blueFont,Element.ALIGN_LEFT,6));
            table.addCell(createCell("公正",blueFont,Element.ALIGN_LEFT,9));

            table.addCell(createCell("和谐",blueFont,Element.ALIGN_LEFT,6));
            table.addCell(createCell("公正",blueFont,Element.ALIGN_LEFT,9));*/
            document.add(table);

            //--------table2--------
            PdfPTable table2 = new PdfPTable(tableCloumns);
            table2.setSpacingAfter(10);
            table2.setSpacingBefore(10);
            table2.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);

            table2.addCell(createCell("状态中心", blueFont, Element.ALIGN_LEFT, tableCloumns, true));


            table2.addCell(createCell("和谐010", blueFont, Element.ALIGN_LEFT, 6, true));
            table2.addCell(createCell("公正", blueFont, Element.ALIGN_LEFT, 9, true));

            table2.addCell(createCell("和谐022", blueFont, Element.ALIGN_LEFT, 6, true));
            table2.addCell(createCell("公正", blueFont, Element.ALIGN_LEFT, 9, true));

            table2.addCell(createCell("1dfjssg", blueFont, Element.ALIGN_LEFT, 6, true));
            table2.addCell(createCell("2asdfa", blueFont, Element.ALIGN_LEFT, 9, true));

            table2.addCell(createCell("", blueFont, Element.ALIGN_LEFT, 6, true));
            table2.addCell(createCell("", blueFont, Element.ALIGN_LEFT, 9, true));

            document.add(table2);
            //--------table3--------
           /* PdfPTable table3 = new PdfPTable(4);
            table3.setSpacingAfter(10);
            table3.setSpacingBefore(10);
            table3.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
            table3.setTotalWidth(288);
            table3.setLockedWidth(true);
            table3.setWidths(new float[]{1,2,1,2});
            //添加单元格
            table3.addCell(createCell("社会主义",blueFont));
            table3.addCell(createCell("镰刀",blueFont));
            table3.addCell(createCell("资本主义",blueFont));
            table3.addCell(createCell("强",blueFont));
            //table3.setHorizontalAlignment(PdfPTable.ALIGN_RIGHT);


            document.add(table3);*/
            document.close();
            writer.close();
            LOGGER.info("pdf生成成功");
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        }
        return null;
    }

 /*   private static PdfPCell createCell(String value,Font font) {
        PdfPCell pdfPCell = new PdfPCell(new Phrase(value,font));
        pdfPCell.setColspan(10);
        //不换行
        pdfPCell.setNoWrap(true);
        //取消边框
        pdfPCell.disableBorderSide(15);
        return pdfPCell;
    }*/
/**------------------------创建表格单元格的方法start----------------------------*/
    /**
     * 创建单元格(指定字体)
     *
     * @param value
     * @param font
     * @return
     */
    public static PdfPCell createCell(String value, Font font) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_LEFT);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setPhrase(new Phrase(value, font));
        //不换行
        cell.setNoWrap(true);
        //取消边框
        cell.disableBorderSide(15);
        return cell;
    }

    /**
     * 创建单元格（指定字体、水平..）
     *
     * @param value
     * @param font
     * @param align
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    /**
     * 创建单元格（指定字体、水平居..、单元格跨x列合并）
     *
     * @param value
     * @param font
     * @param align
     * @param colspan
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int align, int colspan, boolean noWrap) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
        cell.setHorizontalAlignment(align);
        //跨列合并单元格
        cell.setColspan(colspan);
        Phrase elements = new Phrase(value, font);
        /*elements.add(Chunk.NEWLINE);*/
        cell.setPhrase(elements);
        //不换行
        cell.setNoWrap(noWrap);
        //取消边框
        cell.disableBorderSide(15);
        cell.setMinimumHeight(10);
        cell.setUseAscender(true);
        return cell;
    }
    /**
     * 创建单元格（指定字体、水平居..、单元格跨x列合并、设置单元格内边距）
     * @param value
     * @param font
     * @param align
     * @param colspan
     * @param boderFlag
     * @return
     */
/*    public PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setPhrase(new Phrase(value, font));
        cell.setPadding(3.0f);
        if (!boderFlag) {
            cell.setBorder(0);
            cell.setPaddingTop(15.0f);
            cell.setPaddingBottom(8.0f);
        } else if (boderFlag) {
            cell.setBorder(0);
            cell.setPaddingTop(0.0f);
            cell.setPaddingBottom(15.0f);
        }
        return cell;
    }*/

    /**
     * 创建单元格（指定字体、水平..、边框宽度：0表示无边框、内边距）
     *
     * @param value
     * @param font
     * @param align
     * @param borderWidth
     * @param paddingSize
     * @param flag
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align, float[] borderWidth, float[] paddingSize, boolean flag) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        cell.setBorderWidthLeft(borderWidth[0]);
        cell.setBorderWidthRight(borderWidth[1]);
        cell.setBorderWidthTop(borderWidth[2]);
        cell.setBorderWidthBottom(borderWidth[3]);
        cell.setPaddingTop(paddingSize[0]);
        cell.setPaddingBottom(paddingSize[1]);
        if (flag) {
            cell.setColspan(2);
        }
        return cell;
    }

    /**
     * 创建默认列宽，指定列数、水平(居中、右、左)的表格
     *
     * @param colNumber
     * @param align
     * @return
     */
    public PdfPTable createTable(int colNumber, int align) {
        PdfPTable table = new PdfPTable(colNumber);
        try {
            float maxWidth = 100f;
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(align);
            table.getDefaultCell().setBorder(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }

    /**
     * 创建指定列宽、列数的表格
     *
     * @param widths
     * @return
     */
    public PdfPTable createTable(float[] widths) {
        PdfPTable table = new PdfPTable(widths);

        try {
            float maxWidth = 100f;
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.getDefaultCell().setBorder(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }

    /**
     * 创建空白的表格
     *
     * @return
     */
    public PdfPTable createBlankTable() throws IOException, DocumentException {
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
        Font keyfont = new Font(bfChinese);
        PdfPTable table = new PdfPTable(1);
        table.getDefaultCell().setBorder(0);
        table.addCell(createCell("", keyfont));
        table.setSpacingAfter(20.0f);
        table.setSpacingBefore(20.0f);
        return table;
    }
    public static void pdf2Pic(String pdfPath, String pngPath, String imgName) throws Exception{
        //log.info("IcePdf pdfPath : {},  pngPath : {} ,  imgName : {} ", pdfPath,pngPath,imgName);
        org.icepdf.core.pobjects.Document document = new org.icepdf.core.pobjects.Document();
        document.setFile(pdfPath);
        //缩放比例
        float scale = 2.5f;
        //旋转角度
        float rotation = 0f;
        //for循环在pdf文件资料中使用，目前税票就固定一张，所有就注释了
        //for (int i = 0; i < document.getNumberOfPages(); i++) {
        BufferedImage image = (BufferedImage)
                document.getPageImage(0, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale);
        RenderedImage rendImage = image;
        try {
            imgName = imgName + ".png";
            File file = new File(pngPath + File.separator + imgName);
            ImageIO.write(rendImage, "png", file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        image.flush();
        //}
        document.dispose();
    }


    public static void main(String[] args) {
        //系统路径
        /*String property = System.getProperty("user.dir");
        System.out.println(property);*/

        //---相对路径---
       /* File file = new File("src/main/java/com/hhxy/utils/test.pdf");
        if (!file.exists()){
            file.mkdirs();
        }*/
        //createPdf();
        /*String filePath = "E:\\IDEA PROJECT\\hhxy\\hhxy\\hhxy-parent\\test8939973533494948864.pdf";
        try {
            pdf2Pic(filePath, "E:\\IDEA PROJECT\\hhxy\\hhxy\\hhxy-parent", "PT-011001900321-18675195");
        } catch (Exception e) {
            e.printStackTrace();
        }*/

        String path="/app/pmobile/start/log/";
       /* String[] split = path.split("/");
        StringBuilder sb=new StringBuilder();
        sb.append("/"+split[split.length-2]);
        sb.append("/"+split[split.length-1]+"/");*/
        int i = path.indexOf("/");
        System.out.println(i);
    }
}